<template>
  <div>
    <h3>用户列表组件</h3>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 搜索与添加区域 -->
      <el-row :gutter="20">
        <el-col :span="7">
          <el-input
            placeholder="请输入内容"
            v-model="queryInfo.query"
            clearable
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="onSearch"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addDialogVisible = true"
            >添加用户</el-button
          >
        </el-col>
      </el-row>
      <!-- 数据表格 -->
      <el-table :data="userList" style="width: 100%" stripe border>
        <el-table-column type="index" label="#"> </el-table-column>
        <el-table-column prop="username" label="姓名"> </el-table-column>
        <el-table-column prop="email" label="邮箱"> </el-table-column>
        <el-table-column prop="mobile" label="电话"> </el-table-column>
        <el-table-column prop="role_name" label="角色"> </el-table-column>
        <el-table-column prop="mg_state" label="状态" width="80">
          <!-- 定义插槽往其中添加组件 -->
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.mg_state"
              @change="onStateChang(scope.row)"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180">
          <template slot-scope="scope">
            <!-- slot-scope="scope" -->
            <!-- 修改 -->
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="showEdit(scope.row)"
            ></el-button>
            <!-- 删除 -->
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="removeUserById(scope.row.id)"
            ></el-button>
            <!-- 分配角色 -->
            <!-- 提示文本 -->
            <el-tooltip
              class="item"
              effect="dark"
              content="分配角色"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="warning"
                icon="el-icon-setting"
                size="mini"
                @click="showRleDialog(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页导航区域
      @size-change(pagesize改变时触发)
      @current-change(页码发生改变时触发)
      :current-page(设置当前页码)
      :page-size(设置每页的数据条数)
      :total(设置总页数) -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
      <!-- 添加对话框 -->
      <el-dialog
        title="添加用户"
        :visible.sync="addDialogVisible"
        width="50%"
        @close="onClosed"
      >
        <!-- 对话框主体区域 -->

        <el-form
          :model="addModel"
          ref="addFormRef"
          :rules="addRules"
          label-width="100px"
        >
          <!-- 用户名称 -->
          <el-form-item label="用户名称" prop="username">
            <el-input v-model="addModel.username"></el-input>
          </el-form-item>
          <!-- 密码 -->
          <el-form-item label="密码" prop="password">
            <el-input v-model="addModel.password"></el-input>
          </el-form-item>
          <!-- 邮箱 -->
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="addModel.email"></el-input>
          </el-form-item>
          <!-- 电话 -->
          <el-form-item label="电话" prop="mobile">
            <el-input v-model="addModel.mobile"></el-input>
          </el-form-item>
        </el-form>

        <!-- 对话框底部区域 -->
        <span slot="footer" class="dialog-footer">
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addUser">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 修改对话框 -->
      <!-- @close="onClosed" -->
      <el-dialog
        title="修改信息"
        @close="onClosed"
        :visible.sync="isEditShow"
        width="50%"
      >
        <!-- 对话框主体区域 -->

        <el-form
          :model="editModel"
          ref="refEditForm"
          :rules="addRules"
          label-width="100px"
        >
          <!-- 用户名称 -->
          <el-form-item label="用户名称" prop="username">
            <el-input disabled v-model="editModel.username"></el-input>
          </el-form-item>

          <!-- 邮箱 -->
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="editModel.email"></el-input>
          </el-form-item>
          <!-- 电话 -->
          <el-form-item label="电话" prop="mobile">
            <el-input v-model="editModel.mobile"></el-input>
          </el-form-item>
        </el-form>

        <!-- 对话框底部区域 -->
        <span slot="footer" class="dialog-footer">
          <el-button @click="isEditShow = false">取 消</el-button>
          <el-button type="primary" @click="doedit">确 定</el-button>
        </span>
      </el-dialog>

      <!-- 分配角色 -->
      <!-- @close="onEdClosed" -->
      <el-dialog title="修改信息" :visible.sync="isRoleShow" width="50%">
        <!-- 对话框主体区域 -->
        <p>当前用户：{{curUser.username}}</p>
        <p>当前角色：{{curUser.role_name}}</p>
        <p>
          分配新角色：
          <template>
            <el-select v-model="selRoleId" placeholder="请选择">
              <el-option
                v-for="item in selRoleList"
                :key="item.id"
                :label="item.roleName"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </template>
        </p>

        <!-- 对话框底部区域 -->
        <span slot="footer" class="dialog-footer">
          <el-button @click="isRoleShow = false">取 消</el-button>
          <el-button type="primary" @click="primary">确 定</el-button>
        </span>
      </el-dialog></el-card
    >
  </div>
</template>
     

<script>
export default {
  data() {
    return {
      queryInfo: {
        query: '', // 关键字
        pagenum: 1, // 页码
        pagesize: 2, // 页容量
      },
      userList: [], // 保存请求回来的用户列表数据
      total: 0,
      addDialogVisible: false, // 添加表单显示与否
      isEditShow: false, // 修改表单显示与否
      isRoleShow: false, //分配角色显示与否

      selRoleList: [], //角色下拉数据

      curUser: {}, //等待分配的用户

      selRoleId: '', //选中的角色

      // 新增用户信息
      addModel: {
        id: '',
        username: '',
        password: '',
        email: '',
        mobile: '',
      },
      // 修改用户信息

      editModel: {
        id: '',
        username: '',
        email: '',
        mobile: '',
      },
      // 新增校验规则
      addRules: {
        username: [
          { required: true, message: '请输入用户名称', trigger: 'blur' },
          {
            min: 3,
            max: 10,
            message: '用户名在3~10个字符之间',
            trigger: 'blur',
          },
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          {
            min: 6,
            max: 15,
            message: '用户名在6~15个字符之间',
            trigger: 'blur',
          },
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          {
            type: 'email',
            message: '邮箱格式不正确，请重新输入',
            trigger: 'blur',
          },
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          {
            pattern: /^(13|14|15|16|17|18|19)[0-9]\d{8}$/,
            message: '手机号码不正确，请重新输入',
            trigger: 'blur',
          },
        ],
      },
    }
  },
  created() {
    this.getUserList() // 获取用户信息

    this.getRoleList() //获取角色
  },
  methods: {
    // 修改用户对话框信息
    showEdit(user) {
      // 显示对话框
      this.isEditShow = true
      // console.log(user)
      this.editModel.id = user.id
      this.editModel.username = user.username
      this.editModel.email = user.email
      this.editModel.mobile = user.mobile
    },
    doedit() {
      this.$refs.refEditForm.validate(async (valid) => {
        if (valid) {
          const { data: res } = await this.$axios({
            url: 'users/' + this.editModel.id,
            method: 'put',
            data: {
              email: this.editModel.email,
              mobile: this.editModel.mobile,
            },
          })
          console.log(res)
          if (res.meta.status !== 200) return this.$msg.error(res.meta.msg)
          // 关闭并且重新获取数据
          this.isEditShow = false
          this.getUserList()
          this.$msg.success(res.meta.msg)
        }
      })
    },

    // 添加用户
    addUser() {
      // 点击确定按钮，添加新用户
      // 调用validate进行表单验证
      this.$refs.addFormRef.validate(async (valid) => {
        if (!valid) return this.$msg.error('请填写完整用户信息')
        // 发送请求完成添加用户的操作
        const { data: res } = await this.$axios.post('users', this.addModel)

        console.log(res)
        // 判断如果添加失败，就做提示
        if (res.meta.status !== 201) return this.$msg.error('添加用户失败')
        // 添加成功的提示
        this.$msg.success(res.meta.msg)
        // 关闭对话框
        this.addDialogVisible = false
        // 重新请求最新的数据
        this.getUserList()
      })
    },

    // 清空添加表单
    onClosed() {
      this.$refs.addFormRef.resetFields()
    },
    // 清空修改表单
    onEdClosed() {
      this.$refs.refEditForm.resetFields()
    },
    // 搜索
    onSearch() {
      if (this.queryInfo.query.length == 0) {
        return this.$msg.error('请输入内容~')
      }
      // 重新获取
      this.getUserList()
    },
    // 数据请求
    async getUserList() {
      // 发送请求获取用户列表数据
      const { data: res } = await this.$axios.get('users', {
        params: this.queryInfo,
      })
      // console.log(res)
      // 如果返回状态为异常状态则报错并返回
      if (res.meta.status !== 200) return this.$msg.error(res.meta.msg)
      // 如果返回状态正常，将请求的数据保存在data中
      this.userList = res.data.users
      this.total = res.data.total
      // console.log(this.userList, this.total)
    },
    // 页容量更改
    handleSizeChange(newSisz) {
      // console.log(newSisz);
      // 将页容量更改赋值
      this.queryInfo.pagesize = newSisz
      // 重新发送请求
      this.getUserList()
    },
    // 更改页码
    handleCurrentChange(newChang) {
      // console.log(newChang)
      // 更改页码
      this.queryInfo.pagenum = newChang
      // 重新发送请求
      this.getUserList()
    },
    // 根据页码重新获取
    async onStateChang(useinfo) {
      // console.log(useinfo.id)
      const { data: res } = await this.$axios({
        url: `users/${useinfo.id}/state/${useinfo.mg_state}`,
        method: 'put',
      })
      if (res.meta.status !== 200) {
        useinfo.mg_state = !useinfo.mg_state
        return this.$msg.error(res.meta.msg)
      }

      this.$msg.success(res.meta.msg)
    },
    // 删除
    async removeUserById(id) {
      // //弹出确定取消框，是否删除用户
      // const confirmResult = await this.$confirm(
      //   "请问是否要永久删除该用户",
      //   "删除提示",
      //   {
      //     confirmButtonText: "确认删除",
      //     cancelButtonText: "取消",
      //     type: "warning",
      //   }
      // ).catch((err) => err);
      // //如果用户点击确认，则confirmResult 为'confirm'
      // //如果用户点击取消, 则confirmResult获取的就是catch的错误消息'cancel'
      // if (confirmResult != "confirm") {
      //   return this.$message.info("已经取消删除");
      // }

      //发送请求根据id完成删除操作
      const { data: res } = await this.$axios.delete('users/' + id)
      //判断如果删除失败，就做提示
      if (res.meta.status !== 200) return this.$msg.error(res.meta.msg)
      //修改成功的提示
      if (this.userList.length == 1) {
        this.queryInfo.pagenum--
      }

      this.$msg.success(res.meta.msg)
      //重新请求最新的数据
      this.getUserList()
    },
    // 显示角色分配
    showRleDialog(ruser) {
      this.isRoleShow = true
      this.curUser = ruser
    },
    // 获取角色
    async getRoleList() {
      const { data: res } = await this.$axios.get('roles')
      //如果返回状态为异常状态则报错并返回
      if (res.meta.status !== 200) return this.$msg.error(res.meta.msg)
      // //如果返回状态正常，将请求的数据保存在data中
      // this.roleList = res.data
      // console.log(res.data)
      this.selRoleList = res.data
    },

    async primary() {
      const { data: res } = await this.$axios({
        url: `users/${this.curUser.id}/role`,
        method: 'put',
        data: {
          rid: this.selRoleId,
        },
      })
      if (res.meta.status !== 200) return this.$msg.error(res.meta.msg)
      this.isRoleShow = false
      this.getUserList()
    },
  },
}
</script>

<style>
</style>
